import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

import '../models/calendar_event.dart';
import '../providers/calendar_providers.dart';

/// 日历类型过滤器组件
class CalendarTypeFilter extends ConsumerWidget {
  /// 构造函数
  const CalendarTypeFilter({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    // 获取当前选中的事件类型
    final selectedEventType = ref.watch(eventTypeFilterProvider);

    return Container(
      height: 60,
      margin: const EdgeInsets.symmetric(vertical: 8),
      child: ListView(
        scrollDirection: Axis.horizontal,
        padding: const EdgeInsets.symmetric(horizontal: 16),
        children: [
          // 全部事件选项
          _buildFilterChip(
            context,
            ref,
            null,
            '全部',
            Icons.event,
            Colors.blue,
            selectedEventType == null,
          ),
          // 为每种事件类型创建过滤器选项
          for (final eventType in CalendarEventType.values)
            _buildFilterChip(
              context,
              ref,
              eventType,
              _getEventTypeName(eventType),
              eventType.icon.icon!,
              eventType.color,
              selectedEventType == eventType,
            ),
        ],
      ),
    );
  }

  /// 构建过滤器芯片
  Widget _buildFilterChip(
    BuildContext context,
    WidgetRef ref,
    CalendarEventType? eventType,
    String label,
    IconData icon,
    Color color,
    bool isSelected,
  ) {
    return Padding(
      padding: const EdgeInsets.only(right: 8),
      child: FilterChip(
        selected: isSelected,
        label: Text(label),
        avatar: Icon(
          icon,
          color: isSelected ? Colors.white : color,
          size: 18,
        ),
        backgroundColor: Colors.grey.shade200,
        selectedColor: color,
        labelStyle: TextStyle(
          color: isSelected ? Colors.white : Colors.black87,
          fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
        ),
        onSelected: (selected) {
          // 更新选中的事件类型
          ref.read(eventTypeFilterProvider.notifier).state = selected ? eventType : null;
        },
      ),
    );
  }

  /// 获取事件类型名称
  String _getEventTypeName(CalendarEventType eventType) {
    switch (eventType) {
      case CalendarEventType.birthday:
        return '生日';
      case CalendarEventType.play:
        return '游玩';
      case CalendarEventType.medical:
        return '看病';
      case CalendarEventType.anniversary:
        return '纪念日';
      case CalendarEventType.familyGathering:
        return '家庭聚会';
      case CalendarEventType.study:
        return '学习';
      case CalendarEventType.other:
        return '其他';
      default:
        return '未知';
    }
  }
}
